<template>
  <div class="head">
    <!-- <div class="button" @click="handleClick"><a-button type="primary">采集礼物数据</a-button></div> -->
  </div>
</template>
<script lang="ts" setup>
import { getUserLevel,sayMessage,distinguish } from '@/utils/dataUtil'
import {giftsMap} from '@/assets/constant'
// import type { GiftMap } from '@/utils/types'


let commentTimerId: number, welcomeTimerId: number
// let giftsMap = [] as unknown as GiftMap
// const handleClick = () => {
  // giftsMap =  getGiftMap(giftsMap)
  // console.log(giftsMap,'giftsMap');
// }
//发消息给background
chrome.runtime.sendMessage({type:'content',title:'AIassistant',message:'加载AI直播助手成功'})
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
	if (request.type !== 'popup') return
	if (request.flag === 'start') {
		main()
	} else if(request.flag === 'stop') {
		terminate()
	}
	sendResponse(request.flag)
})
// 开始
function main() {
  // giftsMap = getGiftMap()
  commentTimerId = readUserComments()
  welcomeTimerId = welcome()
}
// 终止
function terminate() {
  window.clearInterval(commentTimerId)
	window.clearInterval(welcomeTimerId)
  // giftsMap = []
}
// 欢迎信息获取
function welcome() {
  return window.setInterval(async function () {
    const bottomElements = document.querySelectorAll<HTMLElement>(".webcast-chatroom___bottom-message")
    const currentElement = bottomElements[bottomElements.length - 1];

    const lastMessage = sessionStorage.getItem("MESSAGE_BOTTOM");
    const currentMessage = currentElement && currentElement.innerText;
    // 获取等级图片地址
    const image = currentElement.getElementsByClassName('IK03Li9C')[0].getElementsByTagName('img')[0]
    // 获取名字
    const name = currentElement.getElementsByClassName('LU6dHmmD')[0]?.textContent?.replace('：','')

    // 判断用户等级权限
    if (await getUserLevel(image,'permissionLevel')) {
      // console.log('等级太低');
      return
    }
    // 对比缓存
    if (currentMessage === lastMessage) {
      // console.log("重复进入直播间");
      return;
    }
    sessionStorage.setItem("MESSAGE_BOTTOM", currentMessage);
    let sayText = "欢迎 " + name + '来到直播间！';
    // if (sayText.indexOf("来了") !== -1) {
    //   sayText = currentMessage.replace(/来了$/gi, "");
    //   sayText = "欢迎 " + name + '来到直播间！';
    // }
    console.log(sayText);
    sayMessage(sayText);
  }, 1500);
}

// 评论信息获取
function readUserComments() {
  return window.setInterval(async function () {
    const userCommentsElements = document.querySelectorAll<HTMLElement>('.webcast-chatroom___item')
    // 评论弹幕节点
    const commentsElements = [] as unknown as Array<HTMLElement>
    userCommentsElements.forEach(item => {
      if (item.className.indexOf('fade')===-1) {
        commentsElements.push(item)
      } else {
        // console.log(item.className,'fade');
      }
    })
    if (commentsElements.length<=1) {
      console.log('暂无评论');
      return
    }
    const currentGiftElement = commentsElements[commentsElements.length - 1];
    // 获取完整信息
    let currentMessage = currentGiftElement && currentGiftElement.innerText;

    // 获取名字
    const name = currentGiftElement.getElementsByClassName('LU6dHmmD')[0]?.textContent?.replace('：','')
    // 获取评论内容
    const comment = currentGiftElement.querySelectorAll('.JqBinbea')[0]?.textContent 

    // 礼物信息
    const giftNode = currentGiftElement.querySelectorAll('.JqBinbea')[0].querySelectorAll('img')[0]
    let gift:string = ''
    if (giftNode) {
      const matchKey = giftNode.src.match(/webcast\/.+\.png/gi)
      console.log(matchKey,'matchKey')
      if (matchKey) {
        // gift = giftsMap.find(item=>item.key ===matchKey[0])?.giftName
        for (const k in giftsMap) {
          if (giftsMap[k].includes(matchKey[0])) {
            gift = k
          }
        }
        if (gift === '') {
          console.log('礼物地址已更换',giftNode.src,name)
        }
        const thankMessage = '感谢' + name + '送出的' + gift
        const lastMessage = sessionStorage.getItem("AUDIENCE_GIFT");
      // 对比缓存
      if (thankMessage === lastMessage) {
        console.log("重复礼物");
        return
      }
        sessionStorage.setItem("AUDIENCE_GIFT",thankMessage);
        console.log(thankMessage)
        chrome.runtime.sendMessage({type:'contentComment',name,comment:'',gift})
        sayMessage(thankMessage)
      } else {
        console.log('礼物DOM类名 已更改！需要更换选择器',name);
      }
    } else {
       // 判断用户等级权限
      const image = currentGiftElement.getElementsByClassName('IK03Li9C')[0].getElementsByTagName('img')[0]
      if (await getUserLevel(image,'commentLevel')) {
        // console.log('等级太低');
        return
      }
      const lastMessage = sessionStorage.getItem("MESSAGE_GIFT");
      // 对比缓存
      if (currentMessage === lastMessage) {
        console.log("重复评论");
        return
      }
      sessionStorage.setItem("MESSAGE_GIFT", currentMessage);
  
      console.log(name+"评论: ",comment);
      sayMessage(name+"评论: "+comment);
    }
    chrome.runtime.sendMessage({type:'contentComment',name,comment,gift:''})
    // if (/(这是|这是啥|这是什么)/.test(currentMessage)) {
    //   sayMessage("我是直播语音助理");
    // }
  }, 1500);
}

</script>
<style lang="less" scoped>
.head{
	color: red;
	position: fixed;
	z-index: 100001;
	right: 10px;
	bottom: 10px;
}
</style>